import 'reflect-metadata'
import path from 'path'
import {createKoaServer, useContainer} from 'routing-controllers'
import {Container} from "typedi"
import {Sequelize} from 'sequelize-typescript'
import serve from 'koa-static'
import bodyParser from 'koa-bodyparser'

const koaJwt = require('koa-jwt')
import {MysqlConfig} from 'config'
import {distPath, configs} from './config'
import {responseInterceptor} from "./interceptors/response.interceptors";

useContainer(Container)

const app = createKoaServer({
  cors: true,
  routePrefix: "/api",
  controllers: [`${__dirname}/controllers/**/*{.controller.js,.controller.ts}`],
  middlewares: [`${__dirname}/middlewares/*{.middleware.js,.middleware.ts}`], //挂载全局中间件
  // interceptors: [responseInterceptor]
  // middlewares:[log4Middleware],
  // interceptors: [responseInterceptor]
  // defaults: {
  //   nullResultCode: 404,
  //   undefinedResultCode: 204,
  // }
})


app.use(serve(distPath))
app.use(bodyParser())
/* 路由权限控制 */
app.use(koaJwt({
  secret: 'bqy'
}).unless({
  // 设置login、register等接口，可以不需要认证访问
  path: [/^\/api\/user\/login/,
    /^\/api\/user\/register/,
    /^\/api\/user\/getSMS/,
    /^\/api\/user\/forget/,
    /^((?!\/api).)*$/    // 设置除了私有接口外的其它资源，可以不需要认证访问
  ]
}));

const mysqlConfig = configs.mysql as MysqlConfig

const sequelize = new Sequelize({
  host: mysqlConfig.host[0],
  database: mysqlConfig.database,
  username: mysqlConfig.user,
  password: mysqlConfig.password,
  // 或者一些其他的数据库
  dialect: 'mysql',
  // 加载我们的实体
  modelPaths: [path.resolve(__dirname, `./models/${mysqlConfig.modelPath}`)],
  define: {
    underscored: true,// 字段以下划线（_）来分割（默认是驼峰命名风格）
    freezeTableName: true,
    timestamps: false,//时间戳，启用该配置后会自动添加createdAt、updatedAt两个字段，分别表示创建和更新时间
    paranoid: false // 虚拟删除。启用该配置后，数据不会真实删除，而是添加一个deletedAt属性
  },
  pool: {
    // 连接池的一些相关配置
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
  // operatorsAliases: true,
  timezone: '+08:00',     //  设置时区为北京时间东八区
  // true会在控制台打印每次sequelize操作时对应的SQL命令
  // logging: true,
})

sequelize.sync({alter: true})

export default app
